package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sql.record.*;
import sql.DBManagment;
/**
 * Servlet implementation class myTable
 */
public class myTable extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public myTable() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String username = (String) request.getSession().getAttribute("loggedUser");
		String days[] = {"Sunday","Monday","Tuesday","Wednesday","Thursday"};
		String hours[] = {"0800","0900","1000","1100","1200","1300","1400","1500","1600","1700","1800","1900","2000","2100"};
		out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
		out.println("<!DOCTYPE timetable SYSTEM \"xmlTable/tableDTD.dtd\">");
		String filename = request.getParameter("xsltFile");
		filename = ((filename == null) || (filename == "")) ? "basic.xsl" : filename;
		out.println("<?xml-stylesheet type=\"text/xsl\" href=\"xmlTable/"+filename+"\"?>");

		out.println("<timetable>");
		try {
			List<TableRecord> userCourses = DBManagment.getMyCourses(username);
			List<CourseSchedule> scheduales = new LinkedList<CourseSchedule>();
			for(TableRecord t : userCourses){
				if(t instanceof CourseSchedule){
					scheduales.add((CourseSchedule)t);
				}
			}
			for(String day : days){
				out.println("<day name=\""+ day +"\">");
				for(String hour : hours){
					out.println("<hour time=\""+ hour +"\">");
					for(CourseSchedule cs : scheduales){
						if(days[cs.day].equals(day)){
							if(cs.startHour.intValue() <= (new Integer(hour)).intValue()){
								if(cs.endHour.intValue() > (new Integer(hour)).intValue()){
									out.println("<course name=\"" + cs.courseName + "\" number=\"" + cs.groupNum + "\"/>");
								}
							}
						}
					}
					out.println("</hour>");
				}
				out.println("</day>");
			}

		} catch (ClassNotFoundException e) {
		} catch (SQLException e) {
			
		}
		out.println("</timetable>");		
		out.close();
	}

}
